// ignore_for_file: prefer_const_constructors

import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:multi_shop/models/address.dart';
import 'package:multi_shop/models/order.dart';
import 'package:multi_shop/models/user.dart';
import 'package:multi_shop/pages/order_list.dart';
import 'package:multi_shop/services/order_api.dart';
import 'package:multi_shop/widgets/payDialog.dart';

/// 订单详情页面，可操作按钮
class OrderDetailPage extends StatefulWidget {
  final String orderNo;

  const OrderDetailPage({super.key, required this.orderNo});
  @override
  _OrderDetailPageState createState() => _OrderDetailPageState();
}

// 订单状态: 0=待支付, 1=待发货, 2=待收货, 3=已完成, 4=售后
class _OrderDetailPageState extends State<OrderDetailPage> {
  Address? _address;
  late String orderNo;
  OrderApi orderApi = OrderApi();
  MallOrder? orderDetail;
  UserInfo? userInfo;

  @override
  void initState() {
    super.initState();
    userInfo = GetStorage().read('userInfo');
    orderNo = widget.orderNo;
    _fetchOrderDetail();
  }

  Future<void> _fetchOrderDetail() async {
    final res = await orderApi.detail(orderNo);
    setState(() {
      orderDetail = res;
      _address = res.address;
      debugPrint("_address ${jsonEncode(_address)}");
    });
  }

  Future<void> _changeAddress() async {
    final res = await Get.toNamed('/address');
    if (res is Address) setState(() => _address = res);
  }

  Widget _buildActionButtons() {
    switch (orderDetail?.status) {
      case OrderStatus.pendingPayment:
        return Row(
          children: [
            Expanded(
              child: OutlinedButton(
                onPressed: () {
                  // TODO: 取消订单
                },
                child: Text('取消订单'),
              ),
            ),
            SizedBox(width: 8),
            Expanded(
              child: ElevatedButton(
                onPressed: () {
                  // TODO: 去支付
                  showDialog(
                    context: context,
                    builder: (_) => PayDialog(
                      orderNo: orderNo,
                      amount: orderDetail!.totalAmount,
                      balance: userInfo!.balance,
                      onConfirm: (method, pwd) {
                        debugPrint('选择的支付方式：${method.label}');
                        debugPrint('输入的支付密码：$pwd');
                        // TODO: 调用支付接口
                      },
                    ),
                  );
                },
                child: Text('去支付'),
              ),
            ),
          ],
        );
      case OrderStatus.pendingShipment:
        return Center(
          child: Text('待发货', style: TextStyle(color: Colors.orange)),
        );
      case OrderStatus.pendingDelivery:
        return Expanded(
          child: ElevatedButton(
            onPressed: () {
              // TODO: 确认收货
            },
            child: Text('确认收货'),
          ),
        );
      case OrderStatus.completed:
        return Row(
          children: [
            Expanded(
              child: OutlinedButton(
                onPressed: () {
                  // TODO: 删除订单
                },
                child: Text('删除订单'),
              ),
            ),
            SizedBox(width: 8),
            Expanded(
              child: ElevatedButton(
                onPressed: () {
                  // TODO: 再次购买
                },
                child: Text('再次购买'),
              ),
            ),
          ],
        );
      case OrderStatus.afterSale:
        return Center(
          child: Text('售后中', style: TextStyle(color: Colors.redAccent)),
        );
      default:
        return SizedBox.shrink();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(title: Text('订单详情')),
      body: orderDetail == null
          ? const Center(child: CircularProgressIndicator())
          : Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                children: [
                  // 订单信息
                  Container(
                    padding: EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(8)),
                    ),

                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('订单号：${orderDetail?.orderNo}'),
                        SizedBox(height: 4),
                        Text('下单时间：${orderDetail?.createdAt}'),
                        SizedBox(height: 8),
                        Divider(
                          height: 1,
                          thickness: 1,
                          color: Colors.grey[300],
                        ),
                        InkWell(
                          onTap: () {
                            // 如果订单还在待支付或待发货，就不允许修改地址
                            if (orderDetail?.status ==
                                    OrderStatus.pendingPayment ||
                                orderDetail?.status ==
                                    OrderStatus.pendingShipment) {
                              return;
                            }

                            _changeAddress();
                          },
                          child: Container(
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Row(
                              children: [
                                Icon(
                                  Icons.location_on,
                                  color: Colors.redAccent,
                                ),
                                SizedBox(width: 8),
                                Expanded(
                                  child: Text(
                                    _address != null
                                        ? '${_address!.receiverName} ${_address!.receiverPhone} \n${_address!.city} ${_address!.detailAddress}'
                                        : '请选择收货地址',
                                  ),
                                ),
                                Visibility(
                                  visible:
                                      orderDetail?.status !=
                                          OrderStatus.pendingPayment &&
                                      orderDetail?.status !=
                                          OrderStatus.pendingShipment,
                                  child: Icon(Icons.chevron_right),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 8),
                  // 商品列表
                  Expanded(
                    child: Container(
                      padding: EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(8)),
                      ),
                      child: ListView.separated(
                        itemCount: orderDetail!.items.length,
                        separatorBuilder: (_, __) => Divider(height: 1),
                        itemBuilder: (_, idx) {
                          return Padding(
                            padding: const EdgeInsets.symmetric(
                              vertical: 4,
                              horizontal: 8,
                            ),
                            child: Row(
                              children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(4),
                                  child: Image.network(
                                    orderDetail!.items[idx].imageUrl,
                                    width: 60,
                                    height: 60,
                                    fit: BoxFit.cover,
                                    loadingBuilder: (context, child, progress) {
                                      if (progress == null) {
                                        return child;
                                      }
                                      return Container(
                                        width: 60,
                                        height: 60,
                                        color: Colors.grey[200],
                                        child: Center(
                                          child: SizedBox(
                                            width: 20,
                                            height: 20,
                                            child: CircularProgressIndicator(
                                              strokeWidth: 2,
                                            ),
                                          ),
                                        ),
                                      );
                                    },
                                    errorBuilder: (context, error, stackTrace) {
                                      return Container(
                                        width: 60,
                                        height: 60,
                                        color: Colors.grey[200],
                                        child: Center(
                                          child: Icon(
                                            Icons.broken_image,
                                            color: Colors.grey,
                                          ),
                                        ),
                                      );
                                    },
                                  ),
                                ),
                                SizedBox(width: 12),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        orderDetail!.items[idx].name,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontSize: 16,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      SizedBox(height: 4),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Row(
                                            children: [
                                              Text(
                                                '¥',
                                                style: TextStyle(
                                                  fontSize: 12,
                                                  color: Colors.red,
                                                ),
                                              ),
                                              SizedBox(width: 2),
                                              Text(
                                                orderDetail!.items[idx].price
                                                    .toStringAsFixed(2),
                                                style: TextStyle(
                                                  fontWeight: FontWeight.bold,
                                                  color: Colors.red,
                                                ),
                                              ),
                                            ],
                                          ),
                                          Text(
                                            'x${orderDetail!.items[idx].quantity}',
                                            style: TextStyle(
                                              color: const Color.fromARGB(
                                                255,
                                                128,
                                                128,
                                                128,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                  // 合计
                  Container(
                    color: Colors.white,
                    padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    child: Row(
                      children: [
                        Text('合计：', style: TextStyle(fontSize: 16)),
                        Spacer(),
                        Text(
                          '¥${orderDetail?.totalAmount.toStringAsFixed(2)}',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                  // 操作按钮
                  Container(
                    padding: EdgeInsets.all(16),
                    child: _buildActionButtons(),
                  ),
                ],
              ),
            ),
    );
  }
}
